package com.shsoft.task;


import com.shsoft.MonitorApplication;
import com.shsoft.component.BaseComponent;
import com.shsoft.component.DataComponent;
import com.shsoft.config.PCStatusConstant;
import com.shsoft.entity.HardWareInfo;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.WritableImage;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;

public class CalendarTask implements Runnable{

    @Override
    public void run() {
        long lastTime = 0;
        while (true){
            long currentTime = System.currentTimeMillis() / 1000;
            if(currentTime != lastTime){
                HardWareInfo.calendar = Calendar.getInstance();
                lastTime = currentTime;
                ArrayList<BaseComponent> componentList = MonitorApplication.mainController.communicationComponentList;
                Map<String, WritableImage> componentBaseImageMap = MonitorApplication.mainController.componentBaseImageMap;
                if(componentList.size() > 0 && componentBaseImageMap.size() > 0){
                    for (BaseComponent component : componentList) {
                        if(component.getType() == BaseComponent.ComponentType.DATA){
                            DataComponent dataComponent = (DataComponent) component;
                            // 新的一分钟，所有时间组件都刷新，否则只刷新【秒】组件
                            if((HardWareInfo.getSecond().equals("00") && PCStatusConstant.dateList.contains(dataComponent.getName()))
                            || (!HardWareInfo.getSecond().equals("00") && dataComponent.getName().equals(PCStatusConstant.COMPONENT_DATE_SEC))){
                                Canvas canvas = new Canvas(dataComponent.getBorderWidth(), dataComponent.getBorderHeight());
                                GraphicsContext gc = canvas.getGraphicsContext2D();
                                gc.drawImage(componentBaseImageMap.get(PCStatusConstant.PRE_DATA_COMPONENT + dataComponent.getName()), 0, 0);
                                dataComponent.drawComponentToSmallCanvas(gc);
                                Platform.runLater(() -> {
                                    BufferedImage image = SwingFXUtils.fromFXImage(canvas.snapshot(null, null), null);
                                    MonitorApplication.taskExecutor.execute(new ProcessingImageDataTask(image, dataComponent.getBorderX(), dataComponent.getBorderY(), true));
                                });
                            }
                        }
                    }
                }
            }
            try {
                Thread.sleep(20);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
